// hooks/doc.ts
import { useState, useEffect, useCallback } from 'react';
import { getLocale } from '../components/locales';
import { useRecord } from '../hooks/record';
import { useField } from '../hooks/field';

export const useDocument = () => {
  const [locale, setLocale] = useState<Locales>(getLocale('zh-CN'));
 
  const [documentInfo, setDocumentInfo] = useState<DocumentInfo | null>(null);
  const [sheets, setSheets] = useState<Sheet[]>([]);
  const [activeSheet, setActiveSheet] = useState<Sheet | null>(null);
  // const [fields, setFields] = useState<Field[]>([]);
  // const [records, setRecords] = useState<DocRecord[]>([]);

    const {records,  setRecords,} = useRecord();
  
    // 使用 useField hook
    const {fields, setFields,loadFields,} = useField();

  // 获取主键字段名称，如果没有主键则返回第一个字段名称
  const getPrimaryFieldName = (): string => {
    if (fields.length === 0) return 'ID';
    
    // 查找主键字段
    const primaryField = fields.find(field => field.isPrimary);
    if (primaryField) {
      return primaryField.name;
    }
    
    // 如果没有主键，返回第一个字段
    return fields[0].name;
  };

  // 获取记录的主要显示值
  const getRecordDisplayValue = (record: DocRecord, maxLength: number = 50): string => {
    const primaryFieldName = getPrimaryFieldName();
    const value = record.fields[primaryFieldName];
    
    if (value === null || value === undefined || value === '') {
      return locale.untitled;
    }
    
    let displayValue: string;
    
    // 如果是对象类型的值，尝试提取文本
    if (typeof value === 'object' && value !== null) {
      displayValue = JSON.stringify(value);
    } else {
      displayValue = String(value);
    }
    
    // 限制最大长度
    if (displayValue.length > maxLength) {
      return displayValue.substring(0, maxLength) + '...';
    }
    
    return displayValue;
  };

  // 加载文档信息
  const loadDocumentInfo = useCallback(async () => {
    try {
      const info = await Dingdocs.script.run('getDocumentInfo');
      setDocumentInfo(info);
    } catch (error: any) {
      console.error('Load document info failed:', error);
    }
  }, []);

  // 加载数据表列表
  const loadSheets = useCallback(async () => {
    try {
      const sheetList = await Dingdocs.script.run('getAllSheets');
      setSheets(sheetList);
    } catch (error: any) {
      console.error('Load sheets failed:', error);
    }
  }, []);

  // 加载当前激活的数据表
  const loadActiveSheet = useCallback(async () => {
    try {
      const sheet = await Dingdocs.script.run('getActiveSheet');
      setActiveSheet(sheet);
      if (sheet) {
        // 注意：这里不再直接调用 loadFields，因为 loadFields 已经移到了 useField hook 中
      }
    } catch (error: any) {
      console.error('Load active sheet failed:', error);
    }
  }, []);

  return {
    locale,
    setLocale,
    documentInfo,
    setDocumentInfo,
    sheets,
    setSheets,
    activeSheet,
    setActiveSheet,
    fields,
    setFields,
    records,
    setRecords,
    getPrimaryFieldName,
    getRecordDisplayValue,
    loadDocumentInfo,
    loadSheets,
    loadActiveSheet
  };
};

export const useDocumentEvents = (
  loadDocumentInfo: () => Promise<void>,
  loadSheets: () => Promise<void>,
  loadActiveSheet: () => Promise<void>,
  loadFields: (sheetId?: string) => Promise<void>,
  loadRecords: (sheetId?: string) => Promise<void>,
  activeSheet: Sheet | null
) => {
  const [eventUnsubscribers, setEventUnsubscribers] = useState<Array<() => void>>([]);

  useEffect(() => {
    let unsubscribers: Array<() => void> = [];
    let lastSheetId: string | null = null; // 记录上次的sheetId，避免重复触发
    let debounceTimer: NodeJS.Timeout | null = null; // 防抖定时器

    const setupEvents = () => {
      try {
        // 监听选择变化（包括activeSheet变化）
        const offSelectionChanged = Dingdocs.base.event.onSelectionChanged((selection) => {
          // 只有当sheetId真正变化时才更新状态
          if (selection.sheetId && selection.sheetId !== lastSheetId) {
            lastSheetId = selection.sheetId;
            console.log('Active sheet changed to:', selection.sheetId);
            
            // 使用防抖来避免频繁调用
            if (debounceTimer) {
              clearTimeout(debounceTimer);
            }
            debounceTimer = setTimeout(() => {
              loadActiveSheet();
              loadDocumentInfo(); // 更新文档信息，包括当前表名
            }, 300); // 300ms防抖延迟
          }
        });
        unsubscribers.push(offSelectionChanged);

        // 监听数据表添加事件
        const offSheetInserted = Dingdocs.base.event.onSheetInserted((event) => {
          console.log('Sheet inserted:', event);
          loadSheets();
          loadDocumentInfo();
        });
        unsubscribers.push(offSheetInserted);

        // 监听数据表删除事件
        const offSheetDeleted = Dingdocs.base.event.onSheetDeleted((event) => {
          console.log('Sheet deleted:', event);
          loadSheets();
          loadDocumentInfo();
          // 如果删除的是当前激活的表，重新加载当前表
          loadActiveSheet();
        });
        unsubscribers.push(offSheetDeleted);

        // 监听字段添加事件
        const offFieldInserted = Dingdocs.base.event.onFieldInserted((event) => {
          console.log('Field inserted:', event);
          // 如果是当前表的字段变化，重新加载字段列表
          if (!activeSheet || event.sheetId === activeSheet.id) {
            loadFields();
          }
          loadSheets(); // 更新字段数量
        });
        unsubscribers.push(offFieldInserted);

        // 监听字段修改事件
        const offFieldModified = Dingdocs.base.event.onFieldModified((event) => {
          console.log('Field modified:', event);
          if (!activeSheet || event.sheetId === activeSheet.id) {
            loadFields();
          }
        });
        unsubscribers.push(offFieldModified);

        // 监听字段删除事件
        const offFieldDeleted = Dingdocs.base.event.onFieldDeleted((event) => {
          console.log('Field deleted:', event);
          if (!activeSheet || event.sheetId === activeSheet.id) {
            loadFields(activeSheet?.id);
          }
          loadSheets(); // 更新字段数量
        });
        unsubscribers.push(offFieldDeleted);

        // 监听记录添加事件
        const offRecordInserted = Dingdocs.base.event.onRecordInserted((event) => {
          console.log('Record inserted:', event);
          if (!activeSheet || event.sheetId === activeSheet.id) {
            loadRecords();
          }
        });
        unsubscribers.push(offRecordInserted);

        // 监听记录修改事件
        const offRecordModified = Dingdocs.base.event.onRecordModified((event) => {
          console.log('Record modified:', event);
          if (!activeSheet || event.sheetId === activeSheet.id) {
            loadRecords();
          }
        });
        unsubscribers.push(offRecordModified);

        // 监听记录删除事件
        const offRecordDeleted = Dingdocs.base.event.onRecordDeleted((event) => {
          console.log('Record deleted:', event);
          if (!activeSheet || event.sheetId === activeSheet.id) {
            loadRecords();
          }
        });
        unsubscribers.push(offRecordDeleted);

        // 保存所有取消监听的函数
        setEventUnsubscribers(unsubscribers);
        
        console.log('Event listeners setup completed');
      } catch (error: any) {
        console.error('Failed to setup event listeners:', error);
      }
    };

    setupEvents();

    // 清理函数
    return () => {
      if (debounceTimer) {
        clearTimeout(debounceTimer);
      }
      unsubscribers.forEach(unsubscribe => {
        try {
          unsubscribe();
        } catch (error) {
          console.warn('Failed to unsubscribe event listener:', error);
        }
      });
    };
  }, []); // 这里故意只在组件挂载时运行一次

  // 清理事件监听器
  useEffect(() => {
    return () => {
      eventUnsubscribers.forEach(unsubscribe => {
        try {
          unsubscribe();
        } catch (error) {
          console.warn('Failed to unsubscribe event listener:', error);
        }
      });
    };
  }, [eventUnsubscribers]);

  return { eventUnsubscribers };
};